#include "DBServer.h"
#include "EndianCast.h"
#include "../../include/GTProto.h"
#include "ProxyMgr.h"
#include "Proxy.h"
#include <ut_debug.h>

CDBServer * CDBServer::m_pInstance = NULL;

CDBServer::CDBServer( utility::network::pipe * pPipe ):
    IServer(pPipe)
{

}


CDBServer::~CDBServer(void)
{
}

CDBServer * CDBServer::CreateInstance( utility::network::pipe * pPipe )
{
    if (m_pInstance == NULL)
        m_pInstance = new CDBServer(pPipe);
    return m_pInstance;
}

CDBServer * CDBServer::Instance()
{
    return m_pInstance;        
}

void CDBServer::DestroyInstance()
{
    delete m_pInstance;
    m_pInstance;
}

void CDBServer::on_receive( const char * message, uint32 message_length )
{
    uint32 nProtoID = ntohl(*(uint32 *)message);
    if (nProtoID == GT_FORWARD_NTF_ID)
    {
        GT_FORWARD_NTF_PKG * pkg = (GT_FORWARD_NTF_PKG *)(message + sizeof(nProtoID));
        if (CProxy * pProxy = CProxyMgr::Instance()->Find(ntohll(pkg->nProxyID)))
        {
            size_t nHeaderSize = sizeof(nProtoID) + sizeof(GT_FORWARD_NTF_PKG);
            size_t nMsgSize = ntohl(pkg->nSize);
            if (message_length == nHeaderSize + nMsgSize)
                pProxy->SendClientMsg((void *)(message + nHeaderSize), nMsgSize);
        }
    }
}

void CDBServer::on_established()
{
    LOG(INFO) << "Connected with database server : "<< utility::network::idtoa(m_pPipe->get_remote_id());
}

void CDBServer::on_disconnected()
{
    //LOG(INFO) << "Disconnected from database server : "<< utility::network::idtoa(m_pPipe->get_remote_id());
}

void CDBServer::on_error( int32 error_code, const char * error_message )
{

}

void CDBServer::Release()
{
    DestroyInstance();
}



